package com.live.dengdengtv.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.method.KeyListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;

import com.live.dengdengtv.R;

public class SelectView extends EditText {
	protected Context context;
	private String title;
	private int selectedIndex = -1;
	private String[][] keyValues;
	private boolean initSelect;
	private String beforeKey;
	private String beforeValue;
	protected Handler handler;
	private Drawable background;
	private boolean newActivityInput;
	private boolean multiChoice;//是否多选
	private boolean[] multiResult;//多选结果

	public SelectView(Context context) {
		this(context, null, null, false);
	}

	public SelectView(Context context, final AttributeSet attrs, String title,
			boolean newActivityInput) {
		super(context, attrs);
		this.context = context;
		this.title = title;
		this.newActivityInput = newActivityInput;
		// 设置样式
		// this.setTextAppearance(context, R.style.input_text);
		int id = newActivityInput ? R.drawable.icon_arrow
				: R.drawable.icon_down;
		this.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources()
				.getDrawable(id), null);
		// 单行
		this.setSingleLine(false);
		if (newActivityInput) {
			this.setCompoundDrawablePadding(10);
			// this.setInputType(InputType.TYPE_DATETIME_VARIATION_NORMAL);

			this.setGravity(Gravity.RIGHT);
			this.setCursorVisible(false);

			this.setKeyListener(new KeyListener() {

				public boolean onKeyUp(View view, Editable text, int keyCode,
						KeyEvent event) {
					return false;
				}

				public boolean onKeyOther(View view, Editable text,
						KeyEvent event) {
					return false;
				}

				public boolean onKeyDown(View view, Editable text, int keyCode,
						KeyEvent event) {
					return false;
				}

				public int getInputType() {
					return 0;
				}

				public void clearMetaKeyState(View view, Editable content,
						int states) {

				}
			});
		}

		// 初始化
		// initDropDownList();
		if (attrs != null) {
			TypedArray typedArray = context.obtainStyledAttributes(attrs,
					R.styleable.SelectView);
			String keyValue = typedArray
					.getString(R.styleable.SelectView_keyvalue);
			if (keyValue != null && !"".equals(keyValue)) {
				String[] arr = keyValue.trim().split("@");
				int len = arr.length;
				keyValues = new String[len][2];
				String[] tempArr = new String[2];
				for (int i = 0; i < len; i++) {
					tempArr = arr[i].split("\\^");
					if (tempArr.length == 2) {
						keyValues[i] = tempArr;
					}
				}
			}
			initSelect = typedArray.getBoolean(R.styleable.SelectView_select,
					false);
			
			multiChoice = typedArray.getBoolean(R.styleable.SelectView_multiChoice,
					false);
			
			typedArray.recycle();
		}

		if (initSelect && keyValues != null && keyValues.length > 0) {
			this.setSelectedIndex(0);
		}

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 100) {
					adapter.notifyDataSetChanged();
				}
			}

		};
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP && this.isClickable()) {
			if (selectedListener != null) {
				if (selectedListener.onBeforeSelected()) {
					showDropDownList();
				}
			} else {
				showDropDownList();
			}
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 显示下拉列表
	 * 
	 */
	public void showDropDownList() {
		if (keyValues == null || keyValues.length == 0) {
			return;
		}
		beforeKey = getSelectedKey();
		beforeValue = getSelectedValue();

		if (!newActivityInput) {
			setBackgroundResource(R.drawable.textfield_selected);
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(Html.fromHtml(title));

		if(multiChoice){
			String[] strs = new String[keyValues.length];
			multiResult = new boolean[keyValues.length];
			for (int i = 0; i < keyValues.length; i++) {
				strs[i] = keyValues[i][1];
			}
			builder.setMultiChoiceItems(strs, null, new OnMultiChoiceClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which, boolean isChecked) {
					multiResult[which] = isChecked;
					selectedIndex = which;//多选情况下,selectedIndex为最后一个点选的项
				}
			})
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							
							StringBuilder sb = new StringBuilder("");
							for (int i = 0; i < multiResult.length; i++) {
								if(multiResult[i]){
									sb.append((i+1)+"，");
								}
							}
							if(sb.length()>1){
								sb.deleteCharAt(sb.length()-1);
							}
							setText(sb.toString());
						}
					})
					.setNegativeButton("取消", null);
		}else {
			builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialogInterface, int which) {
					selectedIndex = which;
					setText(keyValues[which][1]);

					if (!newActivityInput) {
						setBackgroundResource(R.drawable.textfield);
					}
					if (selectedListener != null) {
						String afterKey = getSelectedKey();
						if ((beforeKey == null && afterKey != null)
								|| (beforeKey != null && !beforeKey
										.equals(afterKey))) {
							selectedListener.onSelectedChange(beforeKey,
									beforeValue, afterKey, getSelectedValue());
						}
					}
				}
			});
		}
		
		builder.create().show();
	}

	public void setSelectAble(boolean editAble) {
		if ((!editAble && !this.isClickable())
				|| (editAble && this.isClickable())) {
			return;
		}
		this.setFocusable(editAble);
		this.setFocusableInTouchMode(editAble);
		this.setClickable(editAble);
		if (!newActivityInput) {
			this.setCursorVisible(editAble);

			if (editAble) {
				setCompoundDrawablesWithIntrinsicBounds(null, null,
						getResources().getDrawable(R.drawable.icon_down), null);
				setBackgroundDrawable(background);
			} else {
				background = this.getBackground();
				setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
				setBackgroundDrawable(null);
			}
		}
	}

	public boolean isSelected() {
		return keyValues != null && keyValues.length != 0
				&& selectedIndex != -1 && !"".equals(getSelectedValue())
				&& getSelectedValue() != null;
	}

	public int getSelectedIndex() {
		return selectedIndex;
	}

	public String getSelectedKey() {//取出选项中key的值
		if (selectedIndex == -1) {
			return null;
		}
		return keyValues[selectedIndex][0];
	}

	public String getSelectedValue() {//取出选项中value的值
		if (selectedIndex == -1) {
			return null;
		}
		return keyValues[selectedIndex][1];
	}

	public int getOptionsCount() {
		return keyValues == null ? 0 : keyValues.length;
	}

	public void setSelectedIndex(int index) {
		this.selectedIndex = index;
		setText(keyValues[index][1]);
	}

	public void setSelectedKey(String key) {
		int len = keyValues == null ? 0 : keyValues.length;
		if (key == null) {
			return;
		} else {
			for (int i = 0; i < len; i++) {
				if (key.equals(keyValues[i][0])) {
					this.selectedIndex = i;
					setText(keyValues[i][1]);
					return;
				}
			}
		}
	}

	public void setSelectedKeyTradition(String key) {
		int len = keyValues == null ? 0 : keyValues.length;
		for (int i = 0; i < len; i++) {
			if (key.equals(keyValues[i][0])) {
				this.selectedIndex = i;
				setText(keyValues[i][1]);
				if (selectedListener != null) {
					String afterKey = getSelectedKey();
					if ((beforeKey == null && afterKey != null)
							|| (beforeKey != null && !beforeKey
									.equals(afterKey))) {
						selectedListener.onSelectedChange(beforeKey,
								beforeValue, afterKey, getSelectedValue());
					}
				}
				return;
			}
		}
	}

	public void setSelectedValue(String value) {
		int len = keyValues == null ? 0 : keyValues.length;
		for (int i = 0; i < len; i++) {
			if (value.equals(keyValues[i][1])) {
				this.selectedIndex = i;
				setText(value);
				return;
			}
		}
	}
	
	public String getTitle() {
		return title;
	}

	public void clearOptions() {
		keyValues = null;
		setText("");
		selectedIndex = -1;
		beforeKey = null;
		beforeValue = null;
		handler.sendEmptyMessage(100);
		setText("");
	}

	public void setSelectOptions(String[][] keyValues) {
		clearOptions();
		this.keyValues = keyValues;
		handler.sendEmptyMessage(100);
		if (initSelect && keyValues != null && keyValues.length > 0) {
			setSelectedIndex(0);
		}
	}

	public interface OnSelectedListener {
		boolean onBeforeSelected();//判断是否显示选择项

		void onSelectedChange(String beforeKey, String beforeValue,
							  String afterKey, String afterValue);
	}

	private OnSelectedListener selectedListener;

	public OnSelectedListener getSelectedListener() {
		return selectedListener;
	}

	public void setOnSelectedListener(OnSelectedListener selectedListener) {
		this.selectedListener = selectedListener;
	}

	BaseAdapter adapter = new BaseAdapter() {
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView textview = new TextView(context);
			textview.setTextAppearance(context, R.style.input_text);
			ColorStateList csl = (ColorStateList) getResources()
					.getColorStateList(R.color.list_item_dropdown_color);
			textview.setTextColor(csl);
			textview.setText(keyValues[position][1]);
			textview.setGravity(Gravity.CENTER_VERTICAL);
			textview.setPadding(10, 20, 0, 20);
			textview.setBackgroundResource(R.drawable.list_item_bg);
			// textview.setSingleLine(true);
			return textview;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public int getCount() {
			return keyValues == null ? 0 : keyValues.length;
		}
	};
}
